//
//  LZRequestVideoTask.m
//  laziz_Consumer
//
//  Created by xbnzd on 17/3/28.
//  Copyright © 2017年 XBN. All rights reserved.
//

#import "LZRequestVideoTask.h"
#import "LZVideoCacheManager.h"

#import "AFNetworking.h"
#import "extobjc.h"

@interface LZRequestVideoTask ()<NSURLConnectionDataDelegate,NSURLSessionDataDelegate>

@property (nonatomic, strong) NSString *videoLocalTempPath;//本地临时缓存地址
@property (nonatomic, strong) AFURLSessionManager *sessionManager;
@property (nonatomic, strong) __block NSURLSessionDataTask *task;
@property (nonatomic, strong) NSMutableArray *taskArr;
@property (nonatomic, strong) NSFileHandle *fileHandle;

@property (nonatomic, strong) NSURLConnection *connection;

@property (nonatomic, strong) NSURLSession * session;              //会话对象
@property (nonatomic, strong) NSURLSessionDataTask * sessionTask;


@end

@implementation LZRequestVideoTask

- (instancetype)init
{
    self = [super init];
    if (self) {
        _taskArr = @[].mutableCopy;
        _videoLocalTempPath = [[LZVideoCacheManager shareManager] getCacheTemporaryPath];
        if ([[NSFileManager defaultManager] fileExistsAtPath:_videoLocalTempPath]) {
            [[NSFileManager defaultManager] removeItemAtPath:_videoLocalTempPath error:nil];
            [[NSFileManager defaultManager] createFileAtPath:_videoLocalTempPath contents:nil attributes:nil];
        }else{
            [[NSFileManager defaultManager] createFileAtPath:_videoLocalTempPath contents:nil attributes:nil];
        }
    }
    
    return self;
}

#pragma mark  - NSURLSession 下载方式
- (void)loadVideoWithURL:(NSURL *)url offset:(NSUInteger)offset
{
    _url = url;
    _wantDownLoadOffset = offset;
    
    //重置session
    [self.session invalidateAndCancel];
    
//    DLog(@"_______________________________offset____===%lu",(unsigned long)offset);
    
    /*********************************
     如果有第二个请求过来,则清除掉第一次请求的数据,
     ********************************/
    if (self.taskArr.count >= 1) {
        [[NSFileManager defaultManager] removeItemAtPath:_videoLocalTempPath error:nil];
        [[NSFileManager defaultManager] createFileAtPath:_videoLocalTempPath contents:nil attributes:nil];
    }
    
    //记录当前下载的数据量初始化为0
    _currentDownLoadingOffset = 0;
    
    NSURLComponents *actualURLComponents = [[NSURLComponents alloc] initWithURL:url resolvingAgainstBaseURL:NO];
    actualURLComponents.scheme = @"https";
    
    
    NSMutableURLRequest *rq = [NSMutableURLRequest requestWithURL:[actualURLComponents URL] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:20.0];
    
    if (offset > 0 && self.videoLength > 0) {
        [rq addValue:[NSString stringWithFormat:@"bytes=%ld-%ld",(unsigned long)offset, (unsigned long)self.videoLength - 1] forHTTPHeaderField:@"Range"];
    }
    
    self.session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    
    self.sessionTask = [self.session dataTaskWithRequest:rq];
    
    [self.sessionTask resume];

}


#pragma mark - NSURLSessionDataDelegate
//服务器响应
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler {
    
    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
    
    NSDictionary *dic = (NSDictionary *)[httpResponse allHeaderFields] ;
    
    NSString *content = [dic valueForKey:@"Content-Range"];
    NSArray *array = [content componentsSeparatedByString:@"/"];
    NSString *length = array.lastObject;
    
    NSUInteger videoLength;
    
    if ([length integerValue] == 0) {
        videoLength = (NSUInteger)httpResponse.expectedContentLength;
    } else {
        videoLength = [length integerValue];
    }
    
    self.videoLength = videoLength;
    self.mimeType = @"video/mp4";
    
    NSLog(@"_______________=videoleneth= %ld",self.videoLength);
    
    
    [self.taskArr addObject:self.sessionTask];
    
    
    self.fileHandle = [NSFileHandle fileHandleForWritingAtPath:self.videoLocalTempPath];
    
    if (completionHandler) {
        completionHandler(NSURLSessionResponseAllow);
    }
    
}

//服务器返回数据 可能会调用多次
- (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
{
    [self.fileHandle seekToEndOfFile];
    
    [self.fileHandle writeData:data];
    
    self.currentDownLoadingOffset += data.length;
    
//     NSLog(@"=================本地存储的临时文件量==========%ld", (long)[[LZVideoCacheManager shareManager] getCacheTemporarySize]);
//    NSLog(@"*****************当前下载 offset************=%ld",self.currentDownLoadingOffset);
    if (self.lzRequestVideoTaskDelegate && [self.lzRequestVideoTaskDelegate respondsToSelector:@selector(taskDidReciveVideoDataWithTask:)]) {
        [self.lzRequestVideoTaskDelegate taskDidReciveVideoDataWithTask:self];
    }
    
    CGFloat pp = (CGFloat)self.currentDownLoadingOffset/(CGFloat)self.videoLength;
    if (self.lzRequestVideoTaskDelegate && [self.lzRequestVideoTaskDelegate respondsToSelector:@selector(taskStarLoadingWithProgress:)]) {
        [self.lzRequestVideoTaskDelegate taskStarLoadingWithProgress:pp];
    }

}



//请求完成会调用该方法，请求失败则error有值
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
{
    if (error == nil) {
        NSInteger space = self.videoLength - [[LZVideoCacheManager shareManager] getCacheTemporarySize];
        if (space == 0) {
            BOOL success = [[LZVideoCacheManager shareManager] copyTheTemporaryPathToLocalVideoPathWithVideoURL:_url.absoluteString];
            if (success) {
                //copy 成功后清除临时缓存
                [self clearTemporaryData];
                if (self.lzRequestVideoTaskDelegate && [self.lzRequestVideoTaskDelegate respondsToSelector:@selector(taskDidFinishLoadingWithTask:)]) {
                    [self.lzRequestVideoTaskDelegate taskDidFinishLoadingWithTask:self];
                }
            }
        }
    }else{
        if (self.lzRequestVideoTaskDelegate && [self.lzRequestVideoTaskDelegate respondsToSelector:@selector(taskDidFailLoadingWithTask:withError:)]) {
            [self.lzRequestVideoTaskDelegate taskDidFailLoadingWithTask:self withError:error.code];
        }
    }
}

#pragma mark - afnetwork  下载方式
- (void)loadVideoWithURLTTT:(NSURL *)url offset:(NSUInteger)offset
{
    _url = url;
    _wantDownLoadOffset = offset;
    
    DLog(@"___________________________________===%lu",(unsigned long)offset);
    /*********************************
     如果有第二个请求过来,则清除掉第一次请求的数据,
     ********************************/
    //    if (self.taskArr.count >= 1) {
    //        [self cancel];
    //        [[NSFileManager defaultManager] removeItemAtPath:_videoLocalTempPath error:nil];
    //        [[NSFileManager defaultManager] createFileAtPath:_videoLocalTempPath contents:nil attributes:nil];
    //    }
    
    //记录当前下载的数据量初始化为0
    _currentDownLoadingOffset = 0;
    
    //设置schem,在resourceload中设置的schem, 这里下载时必须把schem设置为正确的值
    NSURLComponents *actualURLComponents = [[NSURLComponents alloc] initWithURL:url resolvingAgainstBaseURL:NO];
    actualURLComponents.scheme = @"https";
    
    NSURLSessionConfiguration *configurion = [NSURLSessionConfiguration defaultSessionConfiguration];
    if (!_sessionManager) {
        _sessionManager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configurion];
    }
    
    NSMutableURLRequest *rq = [NSMutableURLRequest requestWithURL:[actualURLComponents URL] cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:20.0];
    if (offset > 0 && self.videoLength > 0) {
        [rq addValue:[NSString stringWithFormat:@"bytes=%ld-%ld",(unsigned long)offset, (unsigned long)self.videoLength - 1] forHTTPHeaderField:@"Range"];
    }
    
    
    
    @weakify(self);
    
    //开始下载
    self.task = [self.sessionManager dataTaskWithRequest:rq
                                          uploadProgress:^(NSProgress * _Nonnull uploadProgress) {
                                              
                                          } downloadProgress:^(NSProgress * _Nonnull downloadProgress) {
                                              
                                              CGFloat pp = (CGFloat)downloadProgress.completedUnitCount/(CGFloat)downloadProgress.totalUnitCount;
                                              @strongify(self);
                                              if (self.lzRequestVideoTaskDelegate && [self.lzRequestVideoTaskDelegate respondsToSelector:@selector(taskStarLoadingWithProgress:)]) {
                                                  dispatch_sync(dispatch_get_main_queue(), ^{
                                                      [self.lzRequestVideoTaskDelegate taskStarLoadingWithProgress:pp];
                                                  });
                                              }
                                              
                                          } completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
                                              DLog(@"**************error==========%ld",error.code);
                                          }];
    
    [self.task resume];
    
    //收到回复
    [self.sessionManager setDataTaskDidReceiveResponseBlock:^NSURLSessionResponseDisposition(NSURLSession * _Nonnull session, NSURLSessionDataTask * _Nonnull dataTask, NSURLResponse * _Nonnull response) {
        
        @strongify(self);
        self.mimeType = response.MIMEType;
        
        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
        
        NSDictionary *dic = (NSDictionary *)[httpResponse allHeaderFields] ;
        
        NSString *content = [dic valueForKey:@"Content-Range"];
        NSArray *array = [content componentsSeparatedByString:@"/"];
        NSString *length = array.lastObject;
        
        NSUInteger videoLength;
        
        if ([length integerValue] == 0) {
            videoLength = (NSUInteger)httpResponse.expectedContentLength;
        } else {
            videoLength = [length integerValue];
        }
        
        self.videoLength = videoLength;
        
        
        DLog(@"===============视频总长度==%ld",self.videoLength);
        self.fileHandle = [NSFileHandle fileHandleForWritingAtPath:self.videoLocalTempPath];
        
        [self.taskArr addObject:self.sessionManager];
        
        if (self.lzRequestVideoTaskDelegate && [self.lzRequestVideoTaskDelegate respondsToSelector:@selector(taskDidReciveVideoLength:mimeType:task:)]) {
            [self.lzRequestVideoTaskDelegate taskDidReciveVideoLength:self.videoLength mimeType:self.mimeType task:self];
        }
        
        return NSURLSessionResponseAllow;
    }];
    
    //收到数据
    [self.sessionManager setDataTaskDidReceiveDataBlock:^(NSURLSession * _Nonnull session, NSURLSessionDataTask * _Nonnull dataTask, NSData * _Nonnull data) {
        
        @strongify(self);
        [self.fileHandle seekToEndOfFile];
        [self.fileHandle writeData:data];
        
        self.currentDownLoadingOffset += data.length;
        
        //           NSLog(@"+++++++++++++++++++=rurrentdownlaod offset=%ld",self.currentDownLoadingOffset);
        if (self.lzRequestVideoTaskDelegate && [self.lzRequestVideoTaskDelegate respondsToSelector:@selector(taskDidReciveVideoDataWithTask:)]) {
            [self.lzRequestVideoTaskDelegate taskDidReciveVideoDataWithTask:self];
        }
        
    }];
    
    
    //下载完成
    [self.sessionManager setTaskDidCompleteBlock:^(NSURLSession * _Nonnull session, NSURLSessionTask * _Nonnull task, NSError * _Nullable error) {
        DLog(@"------------------------------下载完成-------------------==%@",task);
        @strongify(self);
        if (error == nil) {
            NSInteger space = self.videoLength - [[LZVideoCacheManager shareManager] getCacheTemporarySize];
            if (space == 0) {
                BOOL success = [[LZVideoCacheManager shareManager] copyTheTemporaryPathToLocalVideoPathWithVideoURL:self.url.absoluteString];
                if (success) {
                    //copy 成功后清除临时缓存
                    [self clearTemporaryData];
                    if (self.lzRequestVideoTaskDelegate && [self.lzRequestVideoTaskDelegate respondsToSelector:@selector(taskDidFinishLoadingWithTask:)]) {
                        [self.lzRequestVideoTaskDelegate taskDidFinishLoadingWithTask:self];
                    }
                }
            }else{
                //清除临时缓存
                [self clearTemporaryData];
            }
            
        }else{
            //清除临时缓存
            [self clearTemporaryData];
            if (self.lzRequestVideoTaskDelegate && [self.lzRequestVideoTaskDelegate respondsToSelector:@selector(taskDidFailLoadingWithTask:withError:)]) {
                [self.lzRequestVideoTaskDelegate taskDidFailLoadingWithTask:self withError:error.code];
            }
        }
        //
    }];
    
    
}
#pragma mark - 取消请求
- (void)cancel
{
    if (self.task) {
        [self.task cancel];
    }
    
    [self.sessionManager invalidateSessionCancelingTasks:YES];
}

#pragma mark - 清除临时缓存
- (void)clearTemporaryData
{
    [[NSFileManager defaultManager] removeItemAtPath:_videoLocalTempPath error:nil];
}
@end













